import axios from 'axios';
import Qs from 'qs';
import store from '@/store';
import _config from '../config';
import router from '../router';
import { Message } from 'iview';
Message.config({top: 300, duration: 2.5});
const Axios = axios.create({
  baseURL: _config.baseUrl,
  timeout: 10000,
  responseType: 'json',
  withCredentials: true,
});


Axios.interceptors.request.use(
  (config) => {
    const { method } = config;
    if (config.method === 'post') {
      config.data = Qs.stringify(config.data);
      config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    store.commit('setLoadingStatus', true);
    return config;
  },
  error => {
    Promise.reject(error);
  },
);

Axios.interceptors.response.use(
  res => {
    store.commit('setLoadingStatus', false);
    console.log(res);
    // const requestUrl = res.request.responseURL.match(/(\/{1}\w+\/\w+)+/)[0];
    // console.log(`————————————接口：${requestUrl}，正确返回————————————`);
    if (res.data.code == 0) {
      
      return Promise.resolve(res.data);
    } else if (res.data.code == 101100) {
      Message.error({content: '登录超时'});
      router.push({name: 'login'});
    } else {
      Message.error({content: res.data.message});
      return Promise.reject(res.data);
    }
  },
  error => {
    console.log(error);
    store.commit('setLoadingStatus', false);
    if (!error.response) {
      // loadingInstance.close();
      Message.error({content: '系统错误'});
      return Promise.reject(error);
    }
    const errRes = error.response;
    const {
      status,
      data,
      request,
    } = errRes;
    // loadingInstance.close();
    // if (status == 404) return;
    // const requestUrl = request.responseURL.match(/(\/{1}\w+\/\w+)+/)[0];
    const errorInfo = {
      requestUrl,
      message: '系统异常',
      status,
    };
    // console.log(`————————————接口：${requestUrl} ，请求错误————————————`);
    console.dir(error);
    console.table([errorInfo]);
    switch (status - 0) {
      case 401:
        // router.push('login');
        break;
      case 500:
        break;
      case 400:
        break;
      case 404:
        break;
      default:
        break;
    }
    return Promise.reject(error);
  },
);

export default Axios;
